//
//  TTDianpuCommitOrderViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/12.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuCommitOrderViewController.h"
#import "TTCommitOrderHeaderView.h"
#import "TTAddressModel.h"
#import "TTMyAddressViewController.h"
#import "TTShopCartDiamondViewCell.h"
#import "TTShopCartCommodityViewCell.h"
#import "TTShopCartSubDetailModel.h"
#import "YBImageBrowser.h"
#import <TYAlertView.h>
#import <UIView+TYAlertView.h>
#import "TTCommonViewCell.h"
#import "TTCellLabelModel.h"
#import "TTCellLabelArrowModel.h"
#import "TTCommondDataModel.h"
#import "TTExtractAddressViewController.h"
#import "TTCommitSuccessViewController.h"
#import "TTCommitFailViewController.h"

#import "TTCouponViewController.h"
#import "TTCouponModel.h"



#define cellType @"cellTypeKey"
#define cellData @"cellDataKey"
#define titleKey @"titleKey"

static NSString *luoshiCellID = @"shop_commit_luoshi_cell_id";        // 裸石
static NSString *commodityCellID = @"shop_commit_commodity_cell_id";  // 商品
static NSString *infoCellID = @"info_cell_id";      // 信息

typedef enum : NSUInteger {
    CellTypeWithSingle,  //单个
    CellTypeWithInfo    // 信息
} CellType;

@interface TTDianpuCommitOrderViewController ()<UITableViewDelegate, UITableViewDataSource, TTCommitOrderHeaderViewDelegate, TTShopCartDiamondViewCellDelegate>
{
    TTCellLabelArrowModel *couponInfoModel; // 优惠券
    TTCellLabelModel *couponsMoneyModel; // 优惠金额
    CGFloat totalMoney;             // 总金额
    CGFloat couponMoney;    // 优惠券金额
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) TTCommitOrderHeaderView *headerView;

@property (nonatomic, strong) UILabel *totalMoneyLabel;     // 订单总金额

@property (nonatomic, strong) NSMutableArray *couponArray;  // 优惠券

@property (nonatomic, strong) TTCouponModel *selectCPModel;   // 选中的优惠券
@property (nonatomic, copy) NSString *couponGoodsBarCode;   // 优惠券的GoodsBarCode
@property (nonatomic, assign) NSInteger totalCoupon;    // 请求到的优惠券个数

@property (nonatomic, strong) NSArray *shopArray;   // 商品
@property (nonatomic, copy) NSString *plusShopCustomerName;
@property (nonatomic, copy) NSString *plusShopOrderNo;
@property (nonatomic, copy) NSString *sumGoodsPrice;

@end

@implementation TTDianpuCommitOrderViewController

- (instancetype)initWithShopArray:(NSArray<TTShopCartSubDetailModel *> *)shopArray plusShopCustomerName:(nonnull NSString *)plusShopCustomerName plusShopOrderNo:(nonnull NSString *)plusShopOrderNo sumGoodsPrice:(nonnull NSString *)sumGoodsPrice
{
    self = [super init];
    if (self) {
        
        self.shopArray = [[NSArray alloc] initWithArray:shopArray copyItems:YES];;
        self.plusShopCustomerName = plusShopCustomerName;
        self.plusShopOrderNo = plusShopOrderNo;
        self.sumGoodsPrice = sumGoodsPrice;
        
        for (TTShopCartSubDetailModel *model in self.shopArray) {
            NSString *str = [model.GoodsDescribe componentsJoinedByString:@","];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            model.GoodsDescribe = arr;
//            model.GoodsPrice = sumGoodsPrice;
        }
        
        [self.dataArray addObject:@{cellType : @(CellTypeWithSingle), cellData : self.shopArray, titleKey : @"商品列表"}];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提交订单";
    // 地址
    [self getAddressData];
    // 优惠券
    [self getCouponsInfo];
    
    
    // header 设置完毕刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHeaderViewNotify) name:@"refreshHeaderViewNotify_key" object:nil];
}

- (void)refreshHeaderViewNotify
{
    [self.headerView layoutIfNeeded];
    
    [self.tableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    return [dic[cellData] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithSingle) {
        TTShopCartSubDetailModel *detailModel = dic[cellData][indexPath.row];
        if (detailModel.GoodsType == 1) {
            // 裸石
            TTShopCartDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:NO isFromCommitOrder:YES];
            cell.delegate = self;
            return cell;
        } else {
            TTShopCartCommodityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:commodityCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:NO isFromCommitOrder:YES];
            return cell;
        }
    } else {
        TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        cell.model = dic[cellData][indexPath.row];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithInfo) {
        TTCellModel *model = dic[cellData][indexPath.row];
        if ([model isKindOfClass:[TTCellLabelArrowModel class]]) {
            TTCellLabelArrowModel *am = (TTCellLabelArrowModel *)model;
            if ([self respondsToSelector:am.selector]) {
                IMP imp = [self methodForSelector:am.selector];
                void (*func)(id, SEL) = (void *)imp;
                func(self, am.selector);
            }
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithSingle) {
        TTShopCartSubDetailModel *detailModel = dic[cellData][indexPath.row];
        return detailModel.h;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length == 0) {
        return 0;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length == 0) {
        return [UIView new];
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(333333) fontSize:15];
    label.frame = CGRectMake(10, 0, self.view.width - 20, view.height);
    [view addSubview:label];
    return view;
}

#pragma mark - TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate, TTShopCartMultyViewCellDelegate
- (void)clickLookCertificateWithModel:(TTShopCartSubDetailModel *)model
{
    // 查看证书
    [TTLoginSingle lookCertificateWithUrlString:model.CertPic];
    
}


#pragma mark - TTCommitOrderHeaderViewDelegate
// 选择地址
- (void)clickChooseAddressBtnWithHeaderView:(TTCommitOrderHeaderView *)headerView
{
    if (headerView.receiveType == ReceiveTypeWithMail) {
        // 邮寄
        @weakify(self)
        TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
//            [self.headerView setModel:model isMail:YES];
            [self.headerView setModel:model receiveType:ReceiveTypeWithMail];
        }];
        [self.navigationController pushViewController:addressVC animated:YES];
    } else if (headerView.receiveType == ReceiveTypeWithSelfTake){
        // 自提
        @weakify(self)
        TTExtractAddressViewController *extractVC = [[TTExtractAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
//            [self.headerView setModel:model isMail:NO];
            [self.headerView setModel:model receiveType:ReceiveTypeWithSelfTake];
        }];
        [self.navigationController pushViewController:extractVC animated:YES];
    } else if (headerView.receiveType == ReceiveTypeWithSendFactory) {
        NSLog(@"阿萨德进口国");
    }
    
    
//    if (headerView.isMail) {
//        // 邮寄
//        @weakify(self)
//        TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
//            @strongify(self)
//            [self.headerView setModel:model isMail:YES];
//        }];
//        [self.navigationController pushViewController:addressVC animated:YES];
//    } else {
//        // 自提
//        @weakify(self)
//        TTExtractAddressViewController *extractVC = [[TTExtractAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
//            @strongify(self)
//            [self.headerView setModel:model isMail:NO];
//        }];
//        [self.navigationController pushViewController:extractVC animated:YES];
//    }
    
    
}

// 提交订单
- (void)commitOrderAction
{
    // 1. 验证手机号是否填写
    if (self.headerView.phoneTF.text.length == 0) {
        [self.view makeToast:@"请输入下单人手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    // 保存输入下单人的手机号
    [USER_DEFAULT setObject:self.headerView.phoneTF.text forKey:@"order_phone_key"];
    
    // 2. 验证收货地址是否填写
    if (self.headerView.tapBtn.currentTitle.length > 0) {
        [self.view makeToast:self.headerView.tapBtn.currentTitle duration:1 position:CSToastPositionCenter];
        return;
    }
    // 获取优惠券的goodsBarCode
    if (self.selectCPModel == nil) {
        [self commitOrderWithGoodsListArray:self.shopArray couponGoodsBarCode:nil];
    } else {
        @weakify(self)
        [self getCouponGoodsBarCodeWithGoodsListArray:self.shopArray success:^(NSString *couponGoodsBarCode) {
            @strongify(self)
            [self commitOrderWithGoodsListArray:self.shopArray couponGoodsBarCode:couponGoodsBarCode];
        }];
    }
    
    
}

- (void)commitOrderWithGoodsListArray:(NSArray *)goodsListArray couponGoodsBarCode:(NSString *)couponGoodsBarCode
{
    NSMutableArray *goodsList = [NSMutableArray array];
        for (TTShopCartSubDetailModel *dm in goodsListArray) {
            // 把描述转成json字符串
            NSData *describeData = [NSJSONSerialization dataWithJSONObject:dm.GoodsDescribe options:NSJSONWritingFragmentsAllowed error:nil];
            NSString *describeStr = [[NSString alloc] initWithData:describeData encoding:NSUTF8StringEncoding];
            NSDictionary *dic = @{
                @"GoodsBarCode": dm.GoodsBarCode,
                @"GoodsType": @(dm.GoodsType),
                @"GoodsTitle": dm.GoodsTitle,
                @"GoodsImage": dm.GoodsImage,
                @"GoodsDescribe": describeStr,
                @"GoodsPrice": dm.GoodsPrice,
                @"GoodsCertTypeCode": dm.CertType,
                @"GoodsCertType": dm.Cert,
                @"GoodsCertNo": dm.CertNo,
                @"GoodsCertPic": dm.CertPic,
                @"GoodsCertQueryCode": dm.QueryCode,
                @"GoodsNumber": @1,
                @"InlayNumber": dm.InlayNumber ? : @0,
                @"GoodsInlayRelateBarCode": dm.GoodsInlayRelateBarCode ? : @"",
                @"GoodsInlayCertTypeCode": dm.GoodsInlayCertTypeCode ? : @"",
                @"GoodsInlayCertType": dm.GoodsInlayCertType ? : @"",
                @"FactoryLabel": dm.FactoryLabel,
                @"GoodsMadeCircle": dm.MadeCircle ? : @"",
                @"GoodsGrade": dm.ProductGrade,
                @"GoldColor": dm.CustomizedGoldColor,
                @"ClarityCharacteristics": dm.ClarityCharacteristics
            };
            [goodsList addObject:dic];
        }
        
        NSNumber *num = self.headerView.model.isMail ? @1 : @2;
        NSDictionary *dic = @{
            @"WholesalerName": [TTLoginSingle sharedSingle].loginModel.RealName,
            @"ReciveType": num,                            // 1.邮寄 2.自提
            @"BatchSource": @1,                           // 订单来源 1
            @"PlusShopCustomerName": self.plusShopCustomerName,
            @"PlusShopOrderNo": self.plusShopOrderNo,
            @"ReceiverName": self.headerView.model.ReceiverName, // 收货人姓名
            @"ReceiverMobile": self.headerView.model.ReceiverMobile,// 收货人电话
            @"ReceiverProvince": self.headerView.model.Province, // 省
            @"ReceiverCity": self.headerView.model.City,    // 市
            @"ReceiverArea": self.headerView.model.Area, // 区
            @"ReceiverAddress": self.headerView.model.Address, // 地址
            @"OrderMobile": [self.headerView.phoneTF.text removeBlank],  // 填写的手机号
            @"Remark": self.headerView.remarkTF.text,  // 备注
            @"DiscountTicketId": self.selectCPModel.Id,                    // 优惠券的ID
            @"DiscountGoodsBarCode": couponGoodsBarCode ? : @"",       // 优惠券的goodsbarcode
            @"DiscountPrice": self.selectCPModel.CouponMoney ? : @"0",                     // 优惠券的金额
            @"InlayPrice": @0,  // 总镶嵌费
            @"CertPrice": @0, // 总的证书费
            @"OrderRealPayPrice": self.sumGoodsPrice, // 订单总金额
            @"SalesmanAccountId": [TTLoginSingle sharedSingle].loginModel.SalesmanAccountId,
            @"SalesmanAccountName": [TTLoginSingle sharedSingle].loginModel.SalesmanAccountName,
            @"SalesmanMobile": [TTLoginSingle sharedSingle].loginModel.SalesmanMobile,
            @"GoodsList" : goodsList
        };
        
        [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:commitOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 提交成功
            TTCommitSuccessViewController *vc = [[TTCommitSuccessViewController alloc] init];
            vc.isFromDianpu = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
            
            // 提交失败
            TTCommitFailViewController *vc = [[TTCommitFailViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
        } showLoadingInView:self.view];
}

// 获取地址
- (void)getAddressData
{
    NSDictionary *dic = @{
                          @"param.pageIndex" : @(1),
                          @"param.pageSize" : @(10)
                          };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getAddressList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        NSArray *arr = responseObject;
        
        TTAddressModel *model = [TTAddressModel modelWithJSON:arr.firstObject];
        
        self.headerView = [TTCommitOrderHeaderView headerViewWithAddress:model isNeedInset:NO];
//        [self.headerView setModel:model isMail:YES];    // 默认邮寄
        [self.headerView setModel:model receiveType:ReceiveTypeWithMail];
        self.headerView.delegate = self;
        self.headerView.phoneTF.text = [USER_DEFAULT objectForKey:@"order_phone_key"];
        self.tableView.tableHeaderView = self.headerView;
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
    } showLoadingInView:self.view];
}

// 获取优惠券信息
- (void)getCouponsInfo
{
    [self calculatePrice];  // 计算费用
    NSMutableArray *nameArray = [NSMutableArray array];
    NSMutableArray *styleLibraryIdArray = [NSMutableArray array];
    for (TTShopCartSubDetailModel *model in self.shopArray) {
        [nameArray addObject:model.CategoryName ? : @""];
        if (model.GoodsType != 1) {
            [styleLibraryIdArray addObject:model.StyleLibraryId ? : @""];
        }
    }
    NSDictionary *dic = @{
        @"TotalPrice" : @(totalMoney),
        @"PageIndex" : @1,
        @"PageSize" : @100,
        @"CouponState" : @0,
        @"CategoryName" : nameArray,
        @"StyleLibraryId" : styleLibraryIdArray
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSArray *arr = responseObject;
        self.couponArray = [NSMutableArray array];
        for (NSDictionary *subDic in arr) {
            TTCouponModel *cpModel = [TTCouponModel modelWithJSON:subDic];
            [self.couponArray addObject:cpModel];
        }
        self.totalCoupon = arr.count;   // 总优惠券的个数
        // 1.添加剩余的信息
        [self addCellInfoData];
        // 2. footerview
        [self setupFooterViewWithTotalPrice:self->totalMoney];
        // 3.添加底部view
        [self setupBottomView];
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
}

// 计算费用
- (void)calculatePrice
{
    // 3. 计算总金额
    totalMoney = 0.0;
    for (TTShopCartSubDetailModel *model in self.shopArray) {
        totalMoney += model.GoodsPrice.floatValue;
    }
    totalMoney -= couponMoney;
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f", totalMoney];
}

// 获取优惠券的goodsBarCode
- (void)getCouponGoodsBarCodeWithGoodsListArray:(NSArray *)goodsListArray success:(void(^)(NSString *couponGoodsBarCode))success
{
    // 存放最终要提交的商品
    NSMutableArray *arr = [NSMutableArray array];
    for (TTShopCartSubDetailModel *model in goodsListArray) {
        NSDictionary *dic = @{
            @"GoodsBarCode" : model.GoodsBarCode,
            @"StyleCategoryName" : model.CategoryName,
            @"Price" : model.GoodsPrice
        };
        [arr addObject:dic];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:arr forKey:@"GoodsBarCode"];
    [dic setObject:self.selectCPModel.Id forKey:@"CouponId"];
    [dic setObject:self.selectCPModel.CouponMoney forKey:@"CouponPrice"];
    [dic setObject:@(self.selectCPModel.Type) forKey:@"Type"];
    [dic setObject:@(self.selectCPModel.UseRange) forKey:@"UseRange"];
    [dic setObject:self.selectCPModel.StyleLibraryId forKey:@"StyleLibraryId"];
    [dic setObject:self.selectCPModel.StyleLibraryCategory forKey:@"StyleLibraryCategory"];
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponGoodsBarCode_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject[@"GoodsBarCode"]);
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}

- (void)addCellInfoData
{
    NSMutableArray *array = [NSMutableArray array];
    couponInfoModel = [TTCellLabelArrowModel setModelWithTitle:@"优惠券" content:[NSString stringWithFormat:@"%ld张优惠券", self.totalCoupon] selector:@selector(gotoCouponsPage) contentColor:UIColorHex(FF1F1F)];
    [array addObject:couponInfoModel];
    
    couponsMoneyModel = [TTCellLabelModel setModelWithTitle:@"优惠金额" content:@"￥0" contentColor:UIColorHex(FF1F1F)];
    [array addObject:couponsMoneyModel];
    
    [array addObject:[TTCellLabelModel setModelWithTitle:@"配送费用" content:@"￥0" contentColor:UIColorHex(FF1F1F)]];
    
    [self.dataArray addObject:@{cellType : @(CellTypeWithInfo), cellData : array}];
    
    
}

// 去优惠券页面
- (void)gotoCouponsPage
{
    TTCouponViewController *couponVC = [[TTCouponViewController alloc] initWithDataArray:self.couponArray showNotUseCoupon:YES];
    @weakify(self)
    couponVC.selectedCoupon = ^(TTCouponModel * _Nullable couponModel, UIViewController *vc) {
        @strongify(self)
        self.selectCPModel = couponModel;
        [vc.navigationController popViewControllerAnimated:YES];
        if (couponModel == nil) {
            // 不使用优惠券
            self->couponInfoModel.content = [NSString stringWithFormat:@"%ld张优惠券", self.totalCoupon];
            self->couponsMoneyModel.content = @"￥0";
            self->couponMoney = 0.0;
        } else {
            self->couponInfoModel.content = couponModel.Name;
            self->couponsMoneyModel.content = [NSString stringWithFormat:@"￥%@", couponModel.CouponMoney];
            self->couponMoney = couponModel.CouponMoney.floatValue;
        }
        // 计算价格
        [self calculatePrice];
        [self.tableView reloadData];
        
    };
    [self.navigationController pushViewController:couponVC animated:YES];
    
}


- (void)setupFooterViewWithTotalPrice:(CGFloat)totalPrice
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    // 1. 订单
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, footerView.width, 44)];
    topView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:topView];
    
    UILabel *titleLabel = [UILabel labelWithTitle:@"订单应付总金额" color:UIColorHex(333333) fontSize:15];
    [topView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(topView);
    }];
    
    NSString *total = [NSString stringWithFormat:@"￥%.0f", totalPrice];
    _totalMoneyLabel = [UILabel labelWithTitle:total color:UIColorHex(FF1F1F) fontSize:15];
    [topView addSubview:_totalMoneyLabel];
    [_totalMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(topView).mas_offset(-10);
        make.centerY.equalTo(topView);
    }];
    
    // 2. 提示
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(0, topView.bottom + 10, footerView.width, 10)];
    infoView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:infoView];
    
    NSString *str = @"温馨提示：\n1、下单后客服会联系您进行包含工艺、镶嵌等服务的最终确认。\n2、如果对于下的订单有任何疑问，请联系您的专属导购进行确认。\n3、关于订单的最终加价系统只是预估算，最终成交价会有一定偏差。\n4、货品如无质量问题暂不支持退货";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    [attr addAttributes:@{NSForegroundColorAttributeName : UIColorHex(666666), NSFontAttributeName : [UIFont systemFontOfSize:12]} range:[str rangeOfString:@"温馨提示："]];
    [attr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    UILabel *infoLabel = [UILabel labelWithTitle:@"" color:UIColorHex(999999) fontSize:11];
    infoLabel.frame = CGRectMake(10, 10, footerView.width - 20, 10);
    infoLabel.numberOfLines = 0;
    infoLabel.attributedText = attr;
    [infoLabel sizeToFit];
    [infoView addSubview:infoLabel];
    
    infoView.height = infoLabel.height + 20;
    
    footerView.height = infoView.bottom;
    
    self.tableView.tableFooterView = footerView;
    
}

// 提交订单view
- (void)setupBottomView
{
    UIButton *btn = [UIButton createButtonWithTitle:@"提交订单" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(commitOrderAction)];
    [btn setContentEdgeInsets:UIEdgeInsetsMake(-Tabbar_Bottom_height, 0, 0, 0)];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
    }];
}


// 计算cell高度
- (CGFloat)calculateContentHeightWithModel:(TTShopCartSubDetailModel *)model
{
    CGFloat cellImageH = 65 * kScale + 40;
    NSString *content = [model.GoodsDescribe componentsJoinedByString:@"\n"];
    CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 115 * kScale - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 5;
    CGFloat sh = contentH + 35 + 35;
    sh = sh > cellImageH ? sh : cellImageH;
    return sh;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTShopCartDiamondViewCell class] forCellReuseIdentifier:luoshiCellID];
        [_tableView registerClass:[TTShopCartCommodityViewCell class] forCellReuseIdentifier:commodityCellID];
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:infoCellID];
        
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-45);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
